package com.xhwl.centiotdata.action.pedestrian.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.centiotdata.action.pedestrian.IPedestrianAuth;
import com.xhwl.centiotdata.handler.pedestrian.PedestrianIntegrationFactory;
import com.xhwl.centiotdata.handler.pedestrian.PedestrianIntegrationHandler;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationPropertiesDTO;
import com.xhwl.centiotdata.service.cent.*;
import com.xhwl.centiotdata.service.impl.AccountServiceImpl;
import com.xhwl.centiotdata.service.impl.DeviceServiceImpl;
import com.xhwl.centiotdata.service.integrateconfig.IntegrationConfig;
import com.xhwl.common.dto.auth.PedestrianAuthDTO;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.face.QueryFaceDTO;
import com.xhwl.common.dto.cent.sdata.AccountDTO;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.enums.DoorAuthTypeEnum;
import com.xhwl.common.enums.OperationTypeEnum;
import com.xhwl.common.enums.pedestrian.PassMediumEnum;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.auth.AuthAccountMapping;
import com.xhwl.common.pojo.cent.auth.CardInfo;
import com.xhwl.common.pojo.cent.device.Device;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.pojo.cent.pedes.AuthRecord;
import com.xhwl.common.pojo.cent.pedes.ProjectUsedProduct;
import com.xhwl.common.pojo.cent.sdata.Project;
import com.xhwl.common.query.cent.device.DeviceGroupQuery;
import com.xhwl.common.query.cent.sdata.ProjectQuery;
import com.xhwl.common.vo.cent.auth.CardOfUserVO;
import com.xhwl.common.vo.cent.face.QueryFaceVO;
import com.xhwl.common.vo.cent.pedes.ProjectPassWayVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/09/07/ 11:44
 */
@Slf4j
@Service
public class PedestrianAuthImpl implements IPedestrianAuth {

    @Autowired
    IAuthAccountCentService authAccountCentService;
    @Autowired
    private DeviceServiceImpl deviceService;
    @Autowired
    private IAuthRecordCentService authRecordCentService;
    @Autowired
    private IPedestrianCentService pedestrianCentService;

    @Autowired
    private IProjectCentService iProjectCentService;

    @Autowired
    private AccountServiceImpl accountService;
    @Autowired
    private IFaceSkillCentService faceSkillCentService;

    @Autowired
    private IDeviceCentService deviceCentService;

    @Override
    public ResultJson authorize(PedestrianAuthDTO pedestrianAuthDTO, OperationTypeEnum operationType) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        log.info("-------------------------------授权参数:{},操作类型:{}", JSONObject.toJSONString(pedestrianAuthDTO), operationType);

        List<DeviceDTO> device = deviceService.findDevice(null, null, CategoryEnum.DOOR.getId(), pedestrianAuthDTO.getDeviceIdList());
        List<String> thirdDeviceIds = device.stream().map(DeviceDTO::getThirdDeviceId).collect(Collectors.toList());

        if (null != pedestrianAuthDTO.getEnterpriseId()) {
            ProjectQuery query = new ProjectQuery();
            query.setEnterpriseIds(Collections.singletonList(pedestrianAuthDTO.getEnterpriseId()));
            List<Project> projectList = iProjectCentService.list(query);

            for (Project project : projectList) {
                log.info("开始处理项目id为:{},名称为:{}的数据~~", project.getId(), project.getName());
                List<PedestrianIntegrationConfigDTO> configDTOS = this.getConfigDTOList(project.getId());
                if (StringUtils.isEmpty(configDTOS)) {
                    continue;
                }
                for (PedestrianIntegrationConfigDTO configDTO : configDTOS) {
                    PedestrianIntegrationHandler handler = PedestrianIntegrationFactory.getInvokeStrategy(configDTO.getProductId());
                    if (handler == null) {
                        continue;
                    }
                    switch (operationType) {
                        case CREATE:
                            pedestrianAuthDTO.setThirdDeviceIdList(thirdDeviceIds);
                            handler.createAuth(configDTO, pedestrianAuthDTO);
                            break;
                        case UPDATE:
                            handler.updateAuth(configDTO, pedestrianAuthDTO);
                            break;
                        case DELETE:
                            pedestrianAuthDTO.setDeletedThirdDeviceIdList(thirdDeviceIds);
                            handler.deleteAuth(configDTO, pedestrianAuthDTO);
                            break;
                        default:
                            break;
                    }
                }
            }
            return ResultJson.success();

        } else if (null != pedestrianAuthDTO.getProjectId()) {
            List<PedestrianIntegrationConfigDTO> configDTOList = this.getConfigDTOList(pedestrianAuthDTO.getProjectId());
            if (CollectionUtils.isEmpty(configDTOList)) {
                return ResultJson.success("项目未配置人行设备");
            }
            for (PedestrianIntegrationConfigDTO configDTO : configDTOList) {
                log.info("开始处理项目id为:{},产品ID为:{}的数据~~", configDTO.getProjectId(), configDTO.getProductId());
                PedestrianIntegrationHandler handler = PedestrianIntegrationFactory.getInvokeStrategy(configDTO.getProductId());
                if (handler == null) {
                    return ResultJson.success("项目未配置人行设备");
                }
                switch (operationType) {
                    case CREATE:
                        pedestrianAuthDTO.setThirdDeviceIdList(thirdDeviceIds);
                        handler.createAuth(configDTO, pedestrianAuthDTO);
                    case UPDATE:
                        handler.updateAuth(configDTO, pedestrianAuthDTO);
                    case DELETE:
                        pedestrianAuthDTO.setDeletedThirdDeviceIdList(thirdDeviceIds);
                        handler.deleteAuth(configDTO, pedestrianAuthDTO);
                    default:
                        break;
                }
            }
        }
        stopWatch.stop();
        log.info("授权耗时:{}", stopWatch.getTotalTimeMillis());
        return ResultJson.success();

    }

    @Override
    public ResultJson syncAuthorize(PedestrianAuthDTO pedestrianAuthDTO) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        log.info("人行授权{}", JSONObject.toJSONString(pedestrianAuthDTO));
        Integer projectId = pedestrianAuthDTO.getProjectId();
        List<PedestrianIntegrationConfigDTO> configDTOList = this.getConfigDTOList(projectId);
        log.info("=====>供应商配置列表：{}", configDTOList);
        if (CollectionUtils.isEmpty(configDTOList)) {
            return null;
        }
        ResultJson resultJson = null;
        List<AuthAccountMapping> openAccountList = authAccountCentService.list(projectId, pedestrianAuthDTO.getSourceId(), null);
        List<Integer> productIdList = openAccountList.stream().map(AuthAccountMapping::getProductId).collect(Collectors.toList());
        //处理设备
        //如果没有deviceIdList,判断是不是有设备组id
        List<Integer> deviceIds = new ArrayList<>();
        if(CollectionUtils.isEmpty(pedestrianAuthDTO.getDeviceIdList())){
            if (!CollectionUtils.isEmpty(pedestrianAuthDTO.getDeviceGroupIdList())){
                log.info("设备组授权");
                pedestrianAuthDTO.getDeviceGroupIdList().forEach(id->{
                    DeviceGroupQuery deviceGroupQuery = new DeviceGroupQuery();
                    deviceGroupQuery.setId(id);
                    deviceGroupQuery.setSize(500L);
                    deviceGroupQuery.setCurrent(1L);
                    Page<Device> devicePage = deviceCentService.queryRelation(deviceGroupQuery);
                    if (null!=devicePage && !CollectionUtils.isEmpty(devicePage.getRecords())){
                        deviceIds.addAll(devicePage.getRecords().stream().map(Device::getId).collect(Collectors.toList()));
                    }
                });
                pedestrianAuthDTO.setDeviceIdList(deviceIds);
            }
        }
        Map<String, List<DeviceDTO>> deviceMap = this.handleDevice(pedestrianAuthDTO);
        log.info("获取的设备：{}，入参：{}",JSON.toJSONString(deviceMap),JSON.toJSONString(pedestrianAuthDTO));
        if (CollectionUtils.isEmpty(pedestrianAuthDTO.getCardNumberList())) {
            CardOfUserVO cardOfUserVO = new CardOfUserVO();
            cardOfUserVO.setSize(20);
            cardOfUserVO.setCurrent(1);
            cardOfUserVO.setUserId(pedestrianAuthDTO.getSourceId());
            cardOfUserVO.setProjectId(pedestrianAuthDTO.getProjectId());
            List<CardInfo> originInfos = authAccountCentService.getUserCardDetailByUserid(cardOfUserVO).getRecords();
            List<CardInfo> infos = originInfos.stream().filter(s -> s.getStatus().equals(0)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(infos)) {
                pedestrianAuthDTO.setCardNumberList(infos.stream().map(CardInfo::getNumber).collect(Collectors.toList()));
            }
        }

        //处理卡号 获取卡号转换规则后的卡号
        Map<Integer, Map<String, String>> carNumberMap = this.handleCard(pedestrianAuthDTO);
        Map<Integer, Map<String, String>> deletedNumberMap = this.handleDeletedCard(pedestrianAuthDTO);

        // 如果人脸数据为空 查询人脸中台的人脸图片
        if(StringUtils.isEmpty(pedestrianAuthDTO.getFaceUrl())) {
            List<AccountDTO> accountDTOList = accountService.queryAccount(pedestrianAuthDTO.getProjectId(), Arrays.asList(pedestrianAuthDTO.getSourceId()));
            AccountDTO accountDTO = accountDTOList.get(0);
           pedestrianAuthDTO.setPhone(accountDTO.getPhone());
           pedestrianAuthDTO.setAccountName(accountDTO.getName());
            // 从人脸库获取人脸图片地址
            QueryFaceDTO queryFaceDTO = new QueryFaceDTO();
            queryFaceDTO.setAccountId(accountDTO.getId());
            try {
                List<QueryFaceVO> faceVOS = faceSkillCentService.queryFace(queryFaceDTO);
                if (!CollectionUtils.isEmpty(faceVOS)) {
                    int size = faceVOS.size() - 1;
                    pedestrianAuthDTO.setFaceUrl(faceVOS.get(size).getFaceUrl());
                    pedestrianAuthDTO.setFeature(faceVOS.get(size).getFeatures().getFeature());
                }
            } catch (Exception e) {
                log.error("调用人脸失败  {}", e.getMessage());
            }
        }
        if (CollectionUtils.isEmpty(pedestrianAuthDTO.getCardNumberList())) {
            CardOfUserVO cardOfUserVO = new CardOfUserVO();
            cardOfUserVO.setSize(20);
            cardOfUserVO.setCurrent(1);
            cardOfUserVO.setUserId(pedestrianAuthDTO.getSourceId());
            cardOfUserVO.setProjectId(pedestrianAuthDTO.getProjectId());
            List<CardInfo> infos = authAccountCentService.getUserCardDetailByUserid(cardOfUserVO).getRecords();
            if (!CollectionUtils.isEmpty(infos)) {
                pedestrianAuthDTO.setCardNumberList(infos.stream().map(CardInfo::getNumber).collect(Collectors.toList()));
            }
        }

        //获取项目开门方式
        List<ProjectPassWayVO> projectPassWayVOS = pedestrianCentService.queryByProject(projectId);
        log.info("projectPassWayVOS" + projectPassWayVOS);
        OperationTypeEnum operationType = null;
        pedestrianAuthDTO.setSourceCardNumberList(merge(pedestrianAuthDTO.getCardNumberList(), pedestrianAuthDTO.getCardNumber()));
        for (PedestrianIntegrationConfigDTO configDTO : configDTOList) {
            PedestrianAuthDTO productPedestrianAuthDTO = new PedestrianAuthDTO();
            BeanUtils.copyProperties(pedestrianAuthDTO, productPedestrianAuthDTO);
            Integer productId = configDTO.getProductId();
            PedestrianIntegrationHandler handler = PedestrianIntegrationFactory.getInvokeStrategy(productId);
            if (handler == null) {
                continue;
            }
            log.info("供应商授权{}", productId);

            //设置第三方卡号
            this.handleThirdCard(carNumberMap, productId, productPedestrianAuthDTO);

            //处理待删除卡号
            handleDeletedThirdCard(deletedNumberMap, productId, productPedestrianAuthDTO);

            //设置设备第三方id
            if (!CollectionUtils.isEmpty(deviceMap)) {
                try {
                    this.handleThirdDevice(deviceMap, productId, productPedestrianAuthDTO);
                } catch (Exception e) {
                    log.error("设置第三方设备id出错  {}", e.getMessage());
                }

            }
            //判断是否给卡与人脸授权
            this.handleFaceAndCard(productId, productPedestrianAuthDTO, projectPassWayVOS);
            //判断是新增、修改还是删除 在这里判断是因为在业务端没有productId 判断不了对应供应商产品是否已授权
            //如果已经创建第三方id并且授权设备为空 表示删除这个用户所有授权
            //如果已经创建第三方id并且授权设备不为空 表示更新授权
            //如果没有创建人员 则为新建授权
            log.info("授权开始");
            try {
                if (productIdList.contains(productId)) {
                    //获取第三方人员id
                    log.info("productId:{}", productId);
                    for (AuthAccountMapping authAccountMapping : openAccountList) {
                        if (Objects.equals(productId, authAccountMapping.getProductId())) {
                            productPedestrianAuthDTO.setUserOpenId(authAccountMapping.getOpenId());
                        }
                    }
                    log.info("" + pedestrianAuthDTO);

                    if (Objects.equals(productPedestrianAuthDTO.getCardStatus(), 1) || (CollectionUtils.isEmpty(productPedestrianAuthDTO.getCardNumberList())
                            && CollectionUtils.isEmpty(productPedestrianAuthDTO.getDeviceIdList())
                            && StringUtils.isEmpty(productPedestrianAuthDTO.getFaceUrl()))) {
                        operationType = OperationTypeEnum.DELETE;
                    } else {
                        operationType = OperationTypeEnum.UPDATE;
                    }
                } else if (Objects.equals(pedestrianAuthDTO.getType(), Integer.valueOf(DoorAuthTypeEnum.DEPARTURE.getId()))) {
                    operationType = OperationTypeEnum.DELETE;
                } else {
                    operationType = OperationTypeEnum.CREATE;
                }
                productPedestrianAuthDTO.setFaceUrl(pedestrianAuthDTO.getFaceUrl());
                log.info("---------------------------------授权类型:-----------------------------------{}", operationType);
                log.info("---------------------------------授权参数:-----------------------------------{}", JSONObject.toJSONString(productPedestrianAuthDTO));
                switch (operationType) {
                    case CREATE:
                        resultJson = handler.createAuth(configDTO, productPedestrianAuthDTO);
                        break;
                    case UPDATE:
                        resultJson = handler.updateAuth(configDTO, productPedestrianAuthDTO);
                        break;
                    case DELETE:
                        resultJson = handler.deleteAuth(configDTO, productPedestrianAuthDTO);
                        break;
                    default:
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                log.info("授权返回的结果resultJson:{}", JSONObject.toJSONString(resultJson));
                //授权记录 后续根据授权记录定时对授权失败的数据重新授权
                AuthRecord authRecord = new AuthRecord();
                BeanUtils.copyProperties(productPedestrianAuthDTO, authRecord);
                authRecord.setAccountId(productPedestrianAuthDTO.getSourceId());
                authRecord.setAuthBody((JSONObject) JSONObject.toJSON(productPedestrianAuthDTO));
                authRecord.setConfigBody((JSONObject) JSONObject.toJSON(configDTO));
                authRecord.setProductId(productId);
                authRecord.setOperation(Integer.valueOf(operationType == null ? 0 : operationType.getType()));
                authRecord.setSucceeded(resultJson != null && resultJson.getState());
                authRecord.setFailCount(authRecord.getSucceeded() ? 0 : 1);
                authRecord.setRecordId(productPedestrianAuthDTO.getRecordId());
                authRecord.setAccountName(productPedestrianAuthDTO.getAccountName());
                authRecord.setRemark(resultJson != null && !resultJson.getState() ? resultJson.getMessage():"");
                authRecord.setPhone(productPedestrianAuthDTO.getPhone());
                List<String> deviceNameList=new ArrayList<>();
                if (!CollectionUtils.isEmpty(deviceMap.get("all"))) {
                    deviceMap.get("all").forEach(item -> {
                        deviceNameList.add(item.getName());
                    });
                    authRecord.setDeviceNames(String.join(",", deviceNameList));
                }
                authRecordCentService.save(authRecord);
            }
        }
        stopWatch.stop();
        log.info("授权耗时:{}", stopWatch.getTotalTimeMillis());
        return resultJson;
    }

    private void handleDeletedThirdCard(Map<Integer, Map<String, String>> deletedNumberMap, Integer productId, PedestrianAuthDTO pedestrianAuthDTO) {
        Map<String, String> carMap = deletedNumberMap.get(productId);
        if (!CollectionUtils.isEmpty(carMap)) {
            pedestrianAuthDTO.setDeletedCardNumberList(new ArrayList<>(carMap.values()));
        }
    }

    private PedestrianIntegrationConfigDTO getConfigDTO(Integer projectId) {
        List<DeviceProjSupplierCategory> configDTOList = IntegrationConfig.integrationConfigList.stream()
                .filter(configDTO -> projectId.equals(configDTO.getProjectId()) && CategoryEnum.DOOR.getId().equals(configDTO.getProdCategoryId()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(configDTOList)) {
            return null;
        }
        DeviceProjSupplierCategory deviceProjSupplierCategory = configDTOList.get(0);
        PedestrianIntegrationPropertiesDTO propertiesDTO = JSON.toJavaObject(deviceProjSupplierCategory.getProperties(), PedestrianIntegrationPropertiesDTO.class);
        if (propertiesDTO == null) {
            return null;
        }
        PedestrianIntegrationConfigDTO configDTO = new PedestrianIntegrationConfigDTO();
        BeanUtils.copyProperties(propertiesDTO, configDTO);
        configDTO.setProjectId(deviceProjSupplierCategory.getProjectId());
        configDTO.setProductId(deviceProjSupplierCategory.getProductId());
        return configDTO;
    }

    private List<PedestrianIntegrationConfigDTO> getConfigDTOList(Integer projectId) {
        List<DeviceProjSupplierCategory> configDTOList = IntegrationConfig.integrationConfigList.stream()
                .filter(configDTO -> projectId.equals(configDTO.getProjectId()) && CategoryEnum.DOOR.getId().equals(configDTO.getProdCategoryId()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(configDTOList)) {
            return new ArrayList<>();
        }
        List<PedestrianIntegrationConfigDTO> list = new ArrayList<>();
        for (DeviceProjSupplierCategory projSupplierCategory : configDTOList) {
            PedestrianIntegrationPropertiesDTO propertiesDTO = JSON.toJavaObject(projSupplierCategory.getProperties(), PedestrianIntegrationPropertiesDTO.class);
            if (propertiesDTO == null) {
                continue;
            }
            PedestrianIntegrationConfigDTO configDTO = new PedestrianIntegrationConfigDTO();
            BeanUtils.copyProperties(propertiesDTO, configDTO);
            configDTO.setProjectId(projSupplierCategory.getProjectId());
            configDTO.setProductId(projSupplierCategory.getProductId());
            list.add(configDTO);
        }
        return list;
    }


    private List<String> merge(List<String> list, String str) {
        if (list == null) {
            if (StringUtils.isEmpty(str)) {
                return null;
            }
            list = new ArrayList<>();
            list.add(str);
            return list;
        }
        if (!StringUtils.isEmpty(str) && !list.contains(str)) {
            list.add(str);
        }
        return list;
    }

    @SafeVarargs
    private final List<Integer> merge(List<Integer>... list) {
        if (list.length == 0) {
            return new ArrayList<>();
        }
        List<Integer> result = new ArrayList<>();
        for (List<Integer> deviceDTOS : list) {
            if (CollectionUtils.isEmpty(deviceDTOS)) {
                continue;
            }
            result.addAll(deviceDTOS);
        }
        return result;
    }

    private Map<Integer, Map<String, String>> handleCard(PedestrianAuthDTO pedestrianAuthDTO) {
        List<String> cardNumberList = merge(pedestrianAuthDTO.getCardNumberList(), pedestrianAuthDTO.getCardNumber());
        Map<Integer, Map<String, String>> carNumberMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(cardNumberList)) {
            carNumberMap = pedestrianCentService.cardTransition(pedestrianAuthDTO.getProjectId(), cardNumberList);
        }
        return carNumberMap;
    }

    private Map<Integer, Map<String, String>> handleDeletedCard(PedestrianAuthDTO pedestrianAuthDTO) {
        List<String> cardNumberList = pedestrianAuthDTO.getDeletedCardNumberList();
        Map<Integer, Map<String, String>> carNumberMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(cardNumberList)) {
            carNumberMap = pedestrianCentService.cardTransition(pedestrianAuthDTO.getProjectId(), cardNumberList);
        }
        return carNumberMap;
    }


    private void handleThirdCard(Map<Integer, Map<String, String>> carNumberMap, Integer productId, PedestrianAuthDTO pedestrianAuthDTO) {
        Map<String, String> carMap = carNumberMap.get(productId);
        if (!CollectionUtils.isEmpty(carMap)) {
            pedestrianAuthDTO.setCardNumber(carMap.get(pedestrianAuthDTO.getCardNumber()));
            pedestrianAuthDTO.setCardNumberList(new ArrayList<>(carMap.values()));
        }
    }

    private Map<String, List<DeviceDTO>> handleDevice(PedestrianAuthDTO pedestrianAuthDTO) {
        Map<String, List<DeviceDTO>> result = new HashMap<>();
        List<Integer> deviceIdList = pedestrianAuthDTO.getDeviceIdList();
        List<Integer> addedDeviceIdList = pedestrianAuthDTO.getAddedDeviceIdList();
        List<Integer> deletedDeviceIdList = pedestrianAuthDTO.getDeletedDeviceIdList();
        List<DeviceDTO> deviceDTOS = null, addDeviceDTOS = null, deleteDeviceDTOs = null;
        if (!CollectionUtils.isEmpty(deviceIdList)
                || !CollectionUtils.isEmpty(addedDeviceIdList)
                || !CollectionUtils.isEmpty(deletedDeviceIdList)) {
            List<Integer> addDeviceIdList = this.merge(deviceIdList, addedDeviceIdList, deletedDeviceIdList);
            try {
                deviceDTOS = deviceService.findDevice(null, null, CategoryEnum.DOOR.getId(), addDeviceIdList);
            }catch (Exception e) {
                log.error("调用查询设备失败  {}", e.getMessage());
            }
            if (!CollectionUtils.isEmpty(deviceDTOS)) {
                addDeviceDTOS = deviceDTOS.stream().filter(device -> !CollectionUtils.isEmpty(addedDeviceIdList) && addedDeviceIdList.contains(device.getId())).collect(Collectors.toList());
                deleteDeviceDTOs = deviceDTOS.stream().filter(device -> !CollectionUtils.isEmpty(deletedDeviceIdList) && deletedDeviceIdList.contains(device.getId())).collect(Collectors.toList());
                deviceDTOS = deviceDTOS.stream().filter(device -> !CollectionUtils.isEmpty(deviceIdList) && deviceIdList.contains(device.getId())).collect(Collectors.toList());
            }
            result.put("added", addDeviceDTOS);
            result.put("deleted", deleteDeviceDTOs);
            result.put("all", deviceDTOS);
        }
        return result;
    }

    private void handleThirdDevice(Map<String, List<DeviceDTO>> deviceDTOMap, Integer productId, PedestrianAuthDTO pedestrianAuthDTO) {

        List<DeviceDTO> deviceDTOS = deviceDTOMap.getOrDefault("all", new ArrayList<>());
        List<DeviceDTO> addDeviceDTOS = deviceDTOMap.getOrDefault("added", new ArrayList<>());
        List<DeviceDTO> deleteDeviceDTOs = deviceDTOMap.getOrDefault("deleted", new ArrayList<>());

        List<String> thirdDeviceIds = deviceDTOS.stream().filter(deviceDTO -> deviceDTO.getProductId().equals(productId)).map(DeviceDTO::getThirdDeviceId).collect(Collectors.toList());
        List<String> iotDeviceIds = deviceDTOS.stream().filter(deviceDTO -> deviceDTO.getProductId().equals(productId)).map(DeviceDTO::getIotDeviceId).collect(Collectors.toList());

        pedestrianAuthDTO.setThirdDeviceIdList(thirdDeviceIds);
        pedestrianAuthDTO.setAddedThirdDeviceIdList(addDeviceDTOS.stream().filter(deviceDTO -> deviceDTO.getProductId().equals(productId)).map(DeviceDTO::getThirdDeviceId).collect(Collectors.toList()));
        pedestrianAuthDTO.setDeletedThirdDeviceIdList(deleteDeviceDTOs.stream().filter(deviceDTO -> deviceDTO.getProductId().equals(productId)).map(DeviceDTO::getThirdDeviceId).collect(Collectors.toList()));

        pedestrianAuthDTO.setIotDeviceIdList(iotDeviceIds);
        pedestrianAuthDTO.setAddedIotDeviceIdList(addDeviceDTOS.stream().filter(deviceDTO -> deviceDTO.getProductId().equals(productId)).map(DeviceDTO::getIotDeviceId).collect(Collectors.toList()));
        pedestrianAuthDTO.setDeletedIotDeviceIdList(deleteDeviceDTOs.stream().filter(deviceDTO -> deviceDTO.getProductId().equals(productId)).map(DeviceDTO::getIotDeviceId).collect(Collectors.toList()));

    }

    /**
     * 根据项目开门方式配置 判断是否给相应供应商人脸与卡授权
     *
     * @param productId
     * @param pedestrianAuthDTO
     * @param projectPassWayVOS
     */
    private void handleFaceAndCard(Integer productId, PedestrianAuthDTO pedestrianAuthDTO, List<ProjectPassWayVO> projectPassWayVOS) {
        List<String> passWay = projectPassWayVOS.stream()
                .filter(projectPassWayVO -> productId.equals(projectPassWayVO.getProductId()))
                .map(ProjectUsedProduct::getPassWay).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(passWay) || StringUtils.isEmpty(passWay.get(0))) {
            pedestrianAuthDTO.setFaceUrl(null);
            pedestrianAuthDTO.setCardNumber(null);
            pedestrianAuthDTO.setCardNumberList(null);
        }
        List<String> mediumList = Arrays.asList(passWay.get(0).split(","));
        if (!mediumList.contains(String.valueOf(PassMediumEnum.FACE.getId()))) {
            pedestrianAuthDTO.setFaceUrl(null);
        }
        if (!mediumList.contains(String.valueOf(PassMediumEnum.CARD.getId()))) {
            pedestrianAuthDTO.setCardNumber(null);
            pedestrianAuthDTO.setCardNumberList(null);
        }
    }
}
